package ithink.link.base.utils;

import java.util.Random;

/**
 * Created by zaqb on 2017/3/5.
 */
public class ByteHelper {
    public static short toBigEndian(short a) {
        return (short)(((a & 0xFF) << 8) | ((a >> 8) & 0xFF));
    }

    public static int toBigEndian(int a) {
        return (((a & 0xFF) << 24) | (((a >> 8) & 0xFF) << 16) | (((a >> 16) & 0xFF) << 8) | ((a >> 24) & 0xFF));
    }

    public static short toLittleEndian(short a) {
        return (short)((a & 0xFF) | ((a << 8) & 0xFF));
    }

    public static int toLittleEndian(int a) {
        return (int)((a & 0xFF) | ((a << 8) & 0xFF) | ((a << 16) & 0xFF) | ((a << 24) & 0xFF));
    }

    /**
     * 将int转为低字节在前，高字节在后的byte数组（为了适应c或者c++的int的字节数）
     */
    public static byte[] intToBytes(long n) {
        byte[] desByte = new byte[4];
        desByte[0] = (byte) (n & 0xff);
        desByte[1] = (byte) (n >> 8 & 0xff);
        desByte[2] = (byte) (n >> 16 & 0xff);
        desByte[3] = (byte) (n >> 24 & 0xff);
        return desByte;
    }
    /**
     * 将int转为低字节在前，高字节在后的byte数组（为了适应c或者c++的int的字节数）
     */
    public static byte[] shortToBytes(int n) {
        byte[] desByte = new byte[2];
        desByte[0] = (byte) (n & 0xff);
        desByte[1] = (byte) (n >> 8 & 0xff);
        return desByte;
    }

    public static String byte2hex(byte[] b) {
        String hs = "";
        String stmp = "";
        for (int n = 0; n < b.length; n++) {
            stmp = (Integer.toHexString(b[n] & 0XFF));
            if (stmp.length() == 1)
                hs = hs + "0" + stmp;
            else
                hs = hs + stmp;
        }
        return hs.toUpperCase();
    }

    public static byte[] hex2byte(byte[] b) {
        if ((b.length % 2) != 0)
            throw new IllegalArgumentException("长度不是偶数");
        byte[] b2 = new byte[b.length / 2];
        System.out.println(b2.length);
        for (int n = 0; n < b.length; n += 2) {
            String item = new String(b, n, 2);
            b2[n / 2] = (byte) Integer.parseInt(item, 16);
        }
        return b2;
    }


    public static String getRandomString(int length) { //length表示生成字符串的长度
        String base = "abcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }
}
